var express = require('express');
var router = express.Router();
var { Order } = require('../mongoos/index')
// 获取首页数据
router.get('/orders/:date', async (req, res)=> {
    // const order = await Order.findOne({ date: req.params.date });
    // res.json(order || { orders: [] });
    
    const order = await Order.findOne({ date: req.params.date });
    res.json(order || { orders: [] });

})

router.get('/api/orders', async (req, res)=> {
    try {
        const orders = await Order.find();
        console.log(orders[0].orders[1]);
        
        res.json(orders);
      } catch (error) {
        res.status(500).json({ error: 'Failed to fetch orders' });
      }

})

router.post('/api/orders/cancel', async (req, res) => {
  try {
    const { orderId } = req.body;
    console.log('Received orderId:', orderId);

    // 查找并更新订单状态
    const order = await Order.findOneAndUpdate(
        { 'orders.id': orderId }, // 查找订单
        { $set: { 'orders.$.status': 'cancelled' } }, // 更新状态
        { new: true } // 返回更新后的文档
    );

    if (!order) {
        return res.status(404).json({ error: 'Order not found' });
    }
    res.json(order); // 返回更新后的订单
} catch (error) {
    console.error('Cancel error:', error);
    res.status(500).json({ error: 'Failed to cancel order' });
}
  });

// // 获取菜品
// router.get('/dish', async (req, res)=> {
//     let dishes = await Dish.find()
//     res.send({code:200,data:dishes})
// })
// // 获取评价
// router.get('/pinlu', async (req, res)=> {
//     let pinlus = await pinlu.find()

//     res.send({code:200,data:pinlus})
// })
// //修改菜品
// router.post('/updatedish', async (req, res)=> {
//     let dish = await Dish.findByIdAndUpdate(req.body._id, req.body)
//     res.send({code:200,data:dish})
// })
// // 获取菜品详情
// router.get('/deletedish', async (req, res)=> {
//     const { _id } = req.query
//     let dish = await Dish.findOne({_id: _id})
//     res.send({code:200,data:dish})
// })
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
